﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Accout;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Account
{
    public class UpdateAccountHandler : IRequestHandler<UpdateAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accRepo;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateAccountHandler> logger;

        /// <summary>
        /// 通过构造函数注入所需的资源
        /// </summary>
        /// <param name="accRepo">账号仓储</param>
        /// <param name="mapper">automapper 工具</param>
        /// <param name="logger">日志工具</param>
        public UpdateAccountHandler(IBaseRepository<AccountModel> accRepo,IMapper mapper,ILogger<UpdateAccountHandler> logger)
        {
            this.accRepo = accRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 中介者处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdateAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            //根据账号id查找model
            var model = accRepo.GetModel(request.Id);
            if (model == null) {
                result.Data = 0;
                result.Msg = "错误.您要修改的账号不存在!";
                result.Code = ApiEnums.Error;
                return Task.FromResult(result);
            }
             //校验用户名是否重复
            var count = accRepo.GetAll().Where(x=>x.Name==request.Name&&x.Id!=request.Id).Count();
            if (count > 0) {
                result.Data = 0;
                result.Msg = "错误.您要修改的用户名已经存在!";
                result.Code = ApiEnums.Error;
                return Task.FromResult(result);
            }
            //request.Pass = model.Pass;//确保密码不修改
            var acc = mapper.Map(request,model);
           
            var r = accRepo.Update(acc);

            if (r > 0)
            {
                result.Data = r;
                result.Msg = "更新管理员成功!!";
                result.Code = ApiEnums.Success;
            }
            else {
                result.Data = r;
                result.Msg = "更新管理员失败!!";
                result.Code = ApiEnums.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
